//
//  AppDelegate.m
//  KG
//
//  Created by Eugene Braginets on 14.03.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "StartScreenViewController.h"
#import "MainMenuViewController.h"
#import "WebService.h"
#import "DataItem.h"
#import "Place.h"
#import "NewsItem.h"
#import "PlayerItem.h"
#import "EventItem.h"
#import "Competition.h"
#import "Game.h"
#import <QuartzCore/QuartzCore.h>


@implementation AppDelegate
//
@synthesize window = _window;
@synthesize serversAnswer=_serversAnswer;
@synthesize serversRespondsStore=_serversRespondsStore;
@synthesize dataArraysStore=_dataArraysStore;
@synthesize loadPlayers=_loadPlayers;
@synthesize loadNews=_loadNews;
@synthesize countBanner=_countBanner;
@synthesize countMessage=_countMessage;
@synthesize order=_order;
@synthesize timer=_timer;
@synthesize facebook=_facebook;
@synthesize fixturesAndResults=_fixturesAndResults;
@synthesize errors=_errors;
@synthesize timeStamps=_timeStamps;
@synthesize refreshData=_refreshData;
@synthesize timerDataRefresh=_timerDataRefresh;
@synthesize ss=_ss;
@synthesize timeStamp=_timeStamp;

#pragma mark - METHODS
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   
    NSString* zero=[NSString stringWithString:@"0"];
    
    _timeStamps=[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"1337679103",kNewsItem,zero,kPitchItem, @"1336655760", kPlayerItem, zero,kBannerItem, zero, kMessageItem, nil];
//    [self loadData];
    
    NSLog(@"timeStamps: %@",self.timeStamps);
    
    
//    [self getData:kGetChangesURL
//          andType:kChangeItem];
    
    [self getChanges];
    
    //reset countre for banner show
    self.countMessage=0;
    self.countBanner=0;
    self.order=0;
    
    self.errors=0;
    
    //schedule timer for banner show
    self.timer=[NSTimer scheduledTimerWithTimeInterval:7
                    target:self
                  selector:@selector(switchBanner)
                  userInfo:nil
                   repeats:YES];
    
    self.timerDataRefresh =[NSTimer scheduledTimerWithTimeInterval:300
                                                target:self
                                              selector:@selector(getChanges)
                                              userInfo:nil
                                               repeats:YES];


    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
   
    _serversRespondsStore=[[NSMutableDictionary alloc] init];
    _dataArraysStore=[[NSMutableDictionary alloc] init];
    _fixturesAndResults=[[NSMutableDictionary alloc] init];
    

    
    
    self.loadNews=3;
    self.loadPlayers=6;
 
    
//    
//    [self getData:kGetNewsURL
//          andType:kNewsItem];
//    
//    [self getData:kGetMessageURL
//          andType:kMessageItem];
//    
//    [self getData:kGetBannerURL
//          andType:kBannerItem];
    
    int i;
    for (i=0; i<4; i++) {
        
        //get fixtures&results, next 7 days, Senior, All competitions
        
        [self getData:[NSString stringWithFormat:@"%@compLevel=Senior",[kReqArrayFootballFixtures objectAtIndex:i]]
              andType:[NSString stringWithFormat:@"%@%@%@%@",kGameItem,kFootFixtures,[kCompPanel objectAtIndex:i],[kCompLevels objectAtIndex:0]]];
        
        
        [self getData:[NSString stringWithFormat:@"%@compLevel=Senior",[kReqArrayFootballResults objectAtIndex:i]]
              andType:[NSString stringWithFormat:@"%@%@%@%@",kGameItem,kFootResults,[kCompPanel objectAtIndex:i],[kCompLevels objectAtIndex:0]]];
        
        [self getData:[NSString stringWithFormat:@"%@compLevel=Senior",[kReqArrayHurlingFixtures objectAtIndex:i]]
              andType:[NSString stringWithFormat:@"%@%@%@%@",kGameItem,kHurlFixtures,[kCompPanel objectAtIndex:i],[kCompLevels objectAtIndex:0]]];
        
        
        [self getData:[NSString stringWithFormat:@"%@compLevel=Senior",[kReqArrayHurlingResults objectAtIndex:i]]
              andType:[NSString stringWithFormat:@"%@%@%@%@",kGameItem,kHurlResults,[kCompPanel objectAtIndex:i],[kCompLevels objectAtIndex:0]]];
        
    }
    
        [self getData:kGetEventURL
              andType:kEventItem];
    
    
 
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    
    [self createNavigation];
    
    
    return YES;
    
}

#pragma mark - Client-Server methods

- (void) removeKeys:(NSString*)key{
//    NSLog(@"REMOVE KEY: %@",key);
    for (NSString* a in [kDataArrayStore allKeys]) {
        if ([[a substringToIndex:8] isEqualToString:key]) {
            NSLog(@"REMOVE KEY: %@",a);
            [kDataArrayStore removeObjectForKey:a];
        }
    }
}

- (void) getChanges {
    
    [self removeKeys:kGameItem];
    
    [self removeKeys:kEventItem];
    
    [self getData:kGetChangesURL andType:kChangeItem];
    
}

- (void) loadNewsImage{
    int i=0;
    for (i=0; i<1; i+=1) {
//        NSLog (@"i=%d",i);
        
            [self loadImage:[kNewsArray objectAtIndex:i]];
          
    }
}

- (void) loadPlayersImage {
    int i=0;
    for (i=0; i<self.loadPlayers; i+=1) {
        NSLog (@"i=%d",i);
        [self loadImage:[kPlayersArray objectAtIndex:i]];
    }
}


- (void) sendRequest:(NSString*)request {
    NSURL* url=[NSURL URLWithString:request];
    
    NSString* guid=[[NSProcessInfo processInfo] globallyUniqueString];
    
	[[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector: @selector(serverAnswered:)
                                                 name:guid object: nil];	
    WebService* webService=[[WebService alloc] initWithURL:url andRequestID:guid andDataType:@""];
    
    webService=nil;
    
}

- (void) serverAnswered:(NSNotification *)notify {

	NSLog(@"answer: %@",(NSArray*)[[notify object] objectAtIndex:0]);
    NSLog(@"ID: %@",(NSArray*)[[notify object] objectAtIndex:1]);
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:[[notify object] objectAtIndex:1]
                                                  object:nil]; 
    
}

- (void)loadImage:(DataItem*)item {
    
    //    int ind=[index intValue];
    
    if (item.image) {
        NSLog (@"image is already loaded for itemId: %@",item.itemid);
        return;   
    }
    else {
        NSLog (@"loading image for itemId: %@",item.itemid);
    }
    
    NSString *imageAddr=[NSString stringWithString:item.imageAddr];
    
    NSLog (@"ImageUrl: %@", imageAddr);
    NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageAddr]];
    UIImage* image = [[UIImage alloc] initWithData:imageData];
    [item setImage:image];
    
    //    [self performSelectorOnMainThread:@selector(displayImage:) withObject:item waitUntilDone:NO];
}

- (void) switchBanner {
    
//    NSLog(@"Raise event");
    
    
    if (self.order==0) {
        self.countMessage+=1;
        if (self.countMessage>([[self.dataArraysStore objectForKey:kMessageItem] count ]-1)) {
            self.countMessage=0;
        }
    }
    if (self.order==1) {
        self.countBanner+=1;
        if (self.countBanner>([[self.dataArraysStore objectForKey:kBannerItem] count ]-1)) {
            self.countBanner=0;
        }

    }

//    NSLog(@"MessageCount: %d     BannerCount:%d",self.countMessage,self.countBanner);
    self.order=abs(self.order-1); //if 0 - then order=1, if 1, then order=0

//    NSLog(@"order=%d",self.order);
//    NSLog(@"countMessage=%d",self.countMessage);
//    NSLog(@"countBanner=%d",self.countBanner);
//
//    NSLog(@"Difference: %f",[self.timeStamp timeIntervalSinceNow]);
//    self.timeStamp=[NSDate date];
//    
    
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"switchBanner"
     object:nil];
    
}

- (void) getData:(NSString*)request andType:(NSString*)type{
    
    //refresh data array of data states. YES means that data is up to date, NO that it should be loaded
    if ([self.dataArraysStore objectForKey:type]) {
    
        NSArray* msg=[[NSArray alloc] initWithObjects:type,@"ok", nil];
        NSString* method=[type substringToIndex:8];
        [[NSNotificationCenter defaultCenter]
         postNotificationName:method
         object:msg];
        
        NSLog (@"Object is present in datastore %@",type);
        
        return;
    } 
    

    
    //get data
    NSLog (@"GetData request: %@",request);
    NSURL* url=[NSURL URLWithString:request];
    NSString* guid=[[NSProcessInfo processInfo] globallyUniqueString];
    
	[[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector: @selector(gotData:)
                                                 name:guid object: nil];	
    WebService* webService=[[WebService alloc] initWithURL:url andRequestID:guid andDataType:type];
    
    webService=nil;
}


- (void) gotData:(NSNotification *)notify {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:[[notify object] objectAtIndex:1]
                                                  object:nil]; 
    [self.serversRespondsStore setObject:[[notify object] objectAtIndex:0] forKey:[[notify object] objectAtIndex:2]];
//    NSLog(@"Got %@ loaded",[[notify object] objectAtIndex:2]);
//    NSLog (@"Got data: %@",[[notify object] objectAtIndex:0]);
//    NSOperationQueue *queue = [NSOperationQueue new];
    
    
    NSString* methodName=[[notify object] objectAtIndex:2];
    NSString* method=[methodName substringToIndex:8];
    NSLog(@"Method: %@",method);
//    SEL methodSelector;
    if ([method isEqual:kPitchItem]) {
        
        [self parsePitchItem:[[notify object] objectAtIndex:2]];
//        methodSelector=NSSelectorFromString(@"parsePitchItem:");
        NSLog(@"pitch item!");
    }
    if ([method isEqual:kPlayerItem]) {
        [self parsePlayerItem:[[notify object] objectAtIndex:2]];
        //        methodSelector=NSSelectorFromString(@"parsePlayerItem:");
        NSLog(@"player item!");
    }
    if ([method isEqual:kNewsItem]) {
        [self parseNewsItem:[[notify object] objectAtIndex:2]];
        //        methodSelector=NSSelectorFromString(@"parseNewsItem:");
        NSLog(@"news item!");
    }
    if ([method isEqual:kMessageItem]) {
        [self parseMessageItem:[[notify object] objectAtIndex:2]];
        //        methodSelector=NSSelectorFromString(@"parseMessageItem:");
    }
    if ([method isEqual:kBannerItem]) {
        [self parseBannerItem:[[notify object] objectAtIndex:2]];
        //        methodSelector=NSSelectorFromString(@"parseBannerItem:");
    }
    if ([method isEqual:kEventItem]) {
        [self parseEventItem:[[notify object] objectAtIndex:2]];
        //        methodSelector=NSSelectorFromString(@"parseEventItem:");
    }
//    if ([method isEqual:kCompItem]) {
//        [self parseCompItem:[[notify object] objectAtIndex:2]];
//        //        methodSelector=NSSelectorFromString(@"parseCompItem:");
//    }

    if ([method isEqual:kGameItem]) {
        [self parseGameItem:[[notify object] objectAtIndex:2]];
        //        methodSelector=NSSelectorFromString(@"parseGameItem:");
    }

    if ([method isEqual:kChangeItem]) {
        [self parseChangeItem:[[notify object] objectAtIndex:2]];
        //        methodSelector=NSSelectorFromString(@"parseGameItem:");
    }

    return;
//    NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
//                                        initWithTarget:self
//                                        selector:methodSelector
//                                        object:[[notify object] objectAtIndex:2]];
//    [queue addOperation:operation]; 
    
}





#pragma mark - PARSERS
- (void) parsePitchItem:(NSString*) object {
    
 
    NSLog(@"Pitches parser started with %@ object",object);
    NSString* items=[self.serversRespondsStore objectForKey:object];
    items=[items stringByAddingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
    items=[items stringByReplacingOccurrencesOfString:@"%0A" withString:@"%20"];
    items=[items stringByReplacingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
    
    NSError* err;
//    NSLog (@"stored %@ string %@",object, items);
   
    
    NSDictionary *resultsArray = [items objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode error:&err];
    NSLog(@"Error: %@",err);
    
//    NSLog (@"Server's PITCHES answer: %@",resultsArray);
    
    NSArray *answer=[resultsArray objectForKey:@"items"];
    
//    NSLog (@"Server's PITCHES answer1: %@",answer);
    
    
    NSMutableArray* tempArray=[[NSMutableArray alloc] initWithObjects:nil];
    
       
    //PARSE PITCHES
    for (id item in answer) {
        
        Place *itemPlace=[[Place alloc] init];
        
//        NSLog (@"Place item: %@",item);
        
        NSDictionary *itemDict=[item objectForKey:@"item"];
        
        NSString *name=[itemDict objectForKey:@"name"];
        NSString *lat=[itemDict objectForKey:@"lat"];
        NSString *lng=[itemDict objectForKey:@"lng"];
        NSString *itemid=[itemDict objectForKey:@"itemid"];
        NSString *imageAddr=[itemDict objectForKey:@"image"];
        NSString *address=[itemDict objectForKey:@"address"];
       
        NSString *text=@"";
        if ([itemDict objectForKey:@"text"]) text=[itemDict objectForKey:@"text"];
        NSString *flag=[itemDict objectForKey:@"flag"];
        NSString* keywords=[NSString stringWithString:@""];
        if ([itemDict objectForKey:@"keywords"]) keywords=[itemDict objectForKey:@"keywords"];
        
        //            NSLog(@"keywords: %@",keywords);
        
        CLLocationCoordinate2D coord=CLLocationCoordinate2DMake([lat floatValue], [lng floatValue]);
        
        [itemPlace setImage:nil];
        
//                    NSLog (@"%@ name: %@",object, name);
//        //            NSLog (@"%@ itemid: %@",object, itemid);
//                    NSLog (@"%@ ImageAddr: %@",object, imageAddr);
//                    NSLog (@"%@ flag: %@",object, flag);
//                    NSLog (@"%@ text: %@",object, text);
        
        
        [itemPlace setTitle:[name stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        [itemPlace setPlaceID:itemid];
        [itemPlace setImageAddr:imageAddr];
        [itemPlace setCoordinate:coord];
        [itemPlace setFlag:flag];
        [itemPlace setAddress:[address stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//         NSLog(@"Address: %@",itemPlace.address);
        [itemPlace setKeywords:[keywords stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        [itemPlace setText:[text stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

        [itemPlace setObjectid:[object substringToIndex:8]];
        //            NSLog(@"itemPlace.keywords: %@",itemPlace.keywords);   
        [itemPlace setDescription:[myAppDelegate decodeFromURLString:text]];
        //            NSLog(@"description parsed: %@",itemPlace.description);
//        NSLog(@"ObjectID: %@",itemPlace.objectid);
        [tempArray addObject:itemPlace];   
    }
    
    
    NSLog (@"Parsed %d PITCHES places of %@",[tempArray count],object);
    
    [self.dataArraysStore setObject:tempArray forKey:object];
    
    if ([self.dataArraysStore objectForKey:object]) {
        NSLog (@"Stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
    } 
    else {
        NSLog (@"WARNING: Not stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
        
    }

    [self.refreshData setObject:[NSNumber numberWithBool:YES] forKey:kPitchItem];

    
    [[NSNotificationCenter defaultCenter]
     postNotificationName:object
     object:nil];
    
    
}

- (void) parsePlayerItem:(NSString*) object {
    
//    int i;
    
    NSString* items=[self.serversRespondsStore objectForKey:object];
//    NSLog (@"stored %@ string %@",object, items);

     NSError *err;
    
    NSDictionary *resultsArray = [items objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode error:&err];
    
    if (!err) {
        NSLog(@"JSON is OK");
    }
    else {
        NSLog(@"JSON PROBLEMS");
        return;
    }

    
//    NSLog (@"Server's answer: %@",resultsArray);
    
    NSArray *answer=[resultsArray objectForKey:@"items"];
    
    //NSLog (@"Server's answer1: %@",answer);
    
    
    NSMutableArray* tempArray=[[NSMutableArray alloc] initWithObjects:nil];
    
    //PARSE PLAYERS
   
        
//    i=self.loadPlayers;
    for (id item in answer) {
        
        PlayerItem *itemPlayer=[[PlayerItem alloc] init];
        
//        NSLog (@"item: %@",item);
        
        NSDictionary *itemDict=[item objectForKey:@"item"];
        
        NSString *name=[itemDict objectForKey:@"name"];
        //NSLog (@"name: %@",name);
        
        NSString *itemid=[itemDict objectForKey:@"itemid"];
        
        NSString *imageAddr=[itemDict objectForKey:@"image"];
        
        
        NSString *club=[itemDict objectForKey:@"club"];
        NSString *age=[itemDict objectForKey:@"age"];
        NSString *weight=[self decodeFromURLString:[itemDict objectForKey:@"weight"]];
        NSString *height=[self decodeFromURLString:[itemDict objectForKey:@"height"]];
        NSString *career=[self decodeFromURLString:[itemDict objectForKey:@"career"]];
        NSString *nickname=[itemDict objectForKey:@"nickname"];
        NSString *position=[itemDict objectForKey:@"position"]; 
        
        [itemPlayer setRole:position];
        [itemPlayer setNickname:nickname];
        [itemPlayer setClub:club];
        [itemPlayer setAge:age];
        [itemPlayer setWeight:weight];
        [itemPlayer setHeight:height];
        [itemPlayer setCareer:career];
        [itemPlayer setObjectid:[object substringToIndex:8]];
        

        //imageAddr=@"http://www.portchestersc.com/userfiles/P1020801-castle-320x170.png";
        [itemPlayer setImage:nil];
        
        //             NSLog (@"%@ name: %@",object, name);
        //             NSLog (@"%@ itemid: %@",object, itemid);
        //             NSLog (@"%@ ImageAddr: %@",object, imageAddr);
        
//        NSLog(@"ObjectID: %@",itemPlayer.objectid);

        [itemPlayer setName:name];
        [itemPlayer setItemid:itemid];
        [itemPlayer setImageAddr:imageAddr];
        
        [tempArray addObject:itemPlayer];   
        
    }
    
        
    NSLog (@"Parsed %d objects of %@",[tempArray count],object);
    
    [self.dataArraysStore setObject:tempArray forKey:object];
    
    if ([self.dataArraysStore objectForKey:object]) {
        NSLog (@"Stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
    } 
    else {
        NSLog (@"WARNING: Not stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
        
    }
    
    [self.refreshData setObject:[NSNumber numberWithBool:YES] forKey:kPlayerItem];

    [[NSNotificationCenter defaultCenter]
     postNotificationName:object
     object:nil];
    
    
}

- (void) parseNewsItem:(NSString*) object {
    
//    int i;
    
    NSError *err;
    
//    NSString *items=[NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://192.168.0.102"] encoding:NSStringEncodingConversionAllowLossy error:&err];
    
    NSString* items=[self.serversRespondsStore objectForKey:object];

//    NSLog (@"Rettrieved %@ string %@",object, items);
    
    //PLANNED: as long as Russell will take care about 0A error, remove follows 3 lines

    
    items=[items stringByAddingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
    
//    NSLog(@"String encoded %@",items);
    items=[items stringByReplacingOccurrencesOfString:@"%0A" withString:@"%20"];
//    items=[NSString stringWithString:@"{\"item\": {\"name\":\"Kellogg's C√∫l Camps\",\"itemid\":\"485\",\"publishdate\":\"1341489532\",\"image\":\"http://www.kerrygaa.ie/image_pool/403806128.jpg\",\"summary\":\"Marc%20O%20S%C3%A9%20-%20Kerry%27s%20GAA%20C%C3%BAl%20Camps%20Ambassador\"}}"];
    items=[items stringByReplacingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
    
//    NSLog (@"stored %@ string %@",object, items);
    
    
    NSDictionary *resultsArray = [items objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode error:&err];
    
    if (!err) {
        NSLog(@"JSON is OK");
    }
    else {
        NSLog(@"JSON PROBLEMS");
        return;
    }
    
    
    
//    NSLog (@"JSON answer: %@",resultsArray);
    
    NSArray *answer=[resultsArray objectForKey:@"items"];
    
//    NSLog (@"Server's answer1: %@",answer);
    
    
    NSMutableArray* tempArray=[[NSMutableArray alloc] initWithObjects:nil];
    
        
    //PARSE NEWS
//    i=self.loadNews;
    for (id item in answer) {
        
        NewsItem *itemNews=[[NewsItem alloc] init];
        
//        NSLog (@"item: %@",item);
        
        NSDictionary *itemDict=[item objectForKey:@"item"];
        
        NSString *name=[itemDict objectForKey:@"name"];
//        NSLog (@"name: %@",name);
        
        NSString *itemid=[itemDict objectForKey:@"itemid"];
        NSString *publishdate=[itemDict objectForKey:@"publishdate"];
        NSString *summary=[self decodeFromURLString:[itemDict objectForKey:@"summary"]];
        NSString *body=[self decodeFromURLString:[itemDict objectForKey:@"body"]];
        NSString *imageAddr=[itemDict objectForKey:@"image"];
        
        //imageAddr=@"http://www.portchestersc.com/userfiles/P1020801-castle-320x170.png";
        [itemNews setImage:nil];
        
        //            NSLog (@"%@ name: %@",object, name);
        //            NSLog (@"%@ itemid: %@",object, itemid);
        //            NSLog (@"%@ publishdatetimstamp: %@",object, publishdate);
        //            NSLog (@"%@ summary: %@",object, summary);
        //            NSLog (@"%@ ImageAddr: %@",object, imageAddr);
        
        //adding date
        
        [itemNews setName:name];
        [itemNews setSummary:summary];
        int sec=[publishdate intValue];
        [itemNews setPublishdate:[self timeStampToString:sec]];
        [itemNews setPublishdateTimeStamp:[NSNumber numberWithInteger:sec]];
        [itemNews setItemid:itemid];
        [itemNews setImageAddr:imageAddr];
        [itemNews setBody:body];
        [itemNews setObjectid:[object substringToIndex:8]];

        
        [tempArray addObject:itemNews];   
        
    }
    
        
    NSLog (@"Parsed %d objects of %@",[tempArray count],object);
    
    [self.dataArraysStore setObject:tempArray forKey:object];
    
    if ([self.dataArraysStore objectForKey:object]) {
        NSLog (@"Stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
    } 
    else {
        NSLog (@"WARNING: Not stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
        
    }
    
    [self.refreshData setObject:[NSNumber numberWithBool:YES] forKey:kNewsItem];

    
    
    [[NSNotificationCenter defaultCenter]
     postNotificationName:object
     object:nil];
    
    NSOperationQueue *queue=[[NSOperationQueue alloc] init];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
                                        initWithTarget:self
                                        selector:@selector(loadNewsImage)
                                        object:nil];
    [queue addOperation:operation]; 

    
    
//    [self performSelectorInBackground:@selector(loadNewsImage) withObject:nil];
     
}

- (void) parseMessageItem:(NSString*) object {
     
    NSString* items=[self.serversRespondsStore objectForKey:object];
   
    items=[items stringByAddingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
    items=[items stringByReplacingOccurrencesOfString:@"%0A" withString:@"%20"];
    items=[items stringByReplacingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
    
    //NSLog (@"stored %@ string %@",object, items);
    NSDictionary *resultsArray = [items objectFromJSONString];
    //NSLog (@"Server's answer: %@",resultsArray);
    
    NSArray *answer=[resultsArray objectForKey:@"items"];
    
    //NSLog (@"Server's answer1: %@",answer);
    
    
    NSMutableArray* tempArray=[[NSMutableArray alloc] initWithObjects:nil];
    
        
    //PARSE MESSAGES
        
//        NSLog(@"answer: %@",answer);
    for (id item in answer) {
        
        DataItem *itemData=[[DataItem alloc] init];
        
        
        NSDictionary *itemDict=[item objectForKey:@"item"];
        
        //            NSLog(@"item: %@",item);
        NSString *text=[itemDict objectForKey:@"text"];
        NSString *url=[itemDict objectForKey:@"url"];
        
        [itemData setImage:nil];
        
        //                        NSLog (@"%@ url: %@",object, url);
        //            NSLog (@"%@ itemid: %@",object, itemid);
        //            NSLog (@"%@ ImageAddr: %@",object, imageAddr);
        
        [itemData setObjectid:[object substringToIndex:8]];
        [itemData setUrlstring:url];
        [itemData setText:[self decodeFromURLString:text]];
        
        [tempArray addObject:itemData];   
    }
        
        
    NSLog (@"Parsed %d objects of %@",[tempArray count],object);
    
    [self.dataArraysStore setObject:tempArray forKey:object];
    
    if ([self.dataArraysStore objectForKey:object]) {
        NSLog (@"Stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
    } 
    else {
        NSLog (@"WARNING: Not stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
        
    }
    
    [self.refreshData setObject:[NSNumber numberWithBool:YES] forKey:kMessageItem];

    [[NSNotificationCenter defaultCenter]
     postNotificationName:object
     object:nil];
    
    
}

- (void) parseBannerItem:(NSString*) object {
    
    NSString* items=[self.serversRespondsStore objectForKey:object];
    
    items=[items stringByAddingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
    items=[items stringByReplacingOccurrencesOfString:@"%0A" withString:@"%20"];
    items=[items stringByReplacingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
    
    //NSLog (@"stored %@ string %@",object, items);
    NSDictionary *resultsArray = [items objectFromJSONString];
    //NSLog (@"Server's answer: %@",resultsArray);
    
    NSArray *answer=[resultsArray objectForKey:@"items"];
    
    //NSLog (@"Server's answer1: %@",answer);
    
    
    NSMutableArray* tempArray=[[NSMutableArray alloc] initWithObjects:nil];
    
        
    //PARSE BANNERS
    //        NSLog(@"answer: %@",answer);
    
    for (id item in answer) {
        
        DataItem *itemData=[[DataItem alloc] init];
        
        
        NSDictionary *itemDict=[item objectForKey:@"item"];
        
        //            NSLog(@"item: %@",item);
        NSString *imageAddr=[itemDict objectForKey:@"image"];
        NSString *url=[itemDict objectForKey:@"url"];
        
        [itemData setImage:nil];
        
        //            NSLog (@"%@ name: %@",object, name);
        //            NSLog (@"%@ itemid: %@",object, itemid);
        //            NSLog (@"%@ ImageAddr: %@",object, imageAddr);
        
        
        [itemData setImageAddr:imageAddr];
        [itemData setUrlstring:url];
        [itemData setObjectid:[object substringToIndex:8]];

        
        [self loadImage:itemData];
        [tempArray addObject:itemData];   
    }
    
      
    NSLog (@"Parsed %d objects of %@",[tempArray count],object);
    
    [self.dataArraysStore setObject:tempArray forKey:object];
    
    if ([self.dataArraysStore objectForKey:object]) {
        NSLog (@"Stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
    } 
    else {
        NSLog (@"WARNING: Not stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
     }
    
    [self.refreshData setObject:[NSNumber numberWithBool:YES] forKey:kBannerItem];
    
    [[NSNotificationCenter defaultCenter]
     postNotificationName:object
     object:nil];
}

- (void) parseEventItem:(NSString*) object {
    
    NSString* items=[self.serversRespondsStore objectForKey:object];
    
    items=[items stringByAddingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
    items=[items stringByReplacingOccurrencesOfString:@"%0A" withString:@"%20"];
    items=[items stringByReplacingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
    
    //NSLog (@"stored %@ string %@",object, items);
    NSDictionary *resultsArray = [items objectFromJSONString];
    NSLog (@"Server's answer: %@",resultsArray);
    
    NSArray *answer=[resultsArray objectForKey:@"items"];
    
    //NSLog (@"Server's answer1: %@",answer);
    
    
    NSMutableArray* tempArray=[[NSMutableArray alloc] initWithObjects:nil];
    
    //PARSE EVENTS
//    NSLog(@"answer: %@",answer);
    for (id item in answer) {
        
        EventItem *itemData=[[EventItem alloc] init];
        
        NSDictionary *itemDict=[item objectForKey:@"item"];
        
        //            NSLog(@"item: %@",item);
        NSString *name=[itemDict objectForKey:@"title"];
//        NSString *itemid=[itemDict objectForKey:@"itemid"];
//        NSString *imageAddr=[itemDict objectForKey:@"image"];
//        NSString *venue=[itemDict objectForKey:@"venue"];
        NSString *startDate=[itemDict objectForKey:@"date"];
//        NSString *description=[itemDict objectForKey:@"description"];
 
        [itemData setName:[self decodeFromURLString:name]];
//        [itemData setItemid:itemid];
//        [itemData setDescription:[self decodeFromURLString:description]];
//        [itemData setVenue:[self decodeFromURLString:venue]];
//        [itemData setImageAddr:imageAddr];
        int sec=[startDate intValue];
        
        [itemData setStartdate:[self timeStampToString3:sec]];
        [itemData setStartdatetimestamp:[NSNumber numberWithInt:sec]];
        [itemData setObjectid:[object substringToIndex:8]];

        [itemData setImage:nil];
        [tempArray addObject:itemData];   
    }

    NSLog (@"Parsed %d objects of %@",[tempArray count],object);
    
    if ([tempArray count]==0){
        EventItem *itemData=[[EventItem alloc] init];
        [itemData setName:@"NO EVENTS FOUND"];
        [itemData setDescription:@"nodata"];
        [tempArray addObject:itemData];
    }
    
    [self.dataArraysStore setObject:tempArray forKey:object];
    
    if ([self.dataArraysStore objectForKey:object]) {
        NSLog (@"Stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
    } 
    else {
        NSLog (@"WARNING: Not stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
        
    }
    
    [self.refreshData setObject:[NSNumber numberWithBool:YES] forKey:kEventItem];
    
    [[NSNotificationCenter defaultCenter]
     postNotificationName:object
     object:nil];
}


- (void) parseChangeItem:(NSString*) object {
    NSLog(@"Competition parser started!");
    NSString* items=[self.serversRespondsStore objectForKey:object];
   
//    
//    NSString* items=[NSString stringWithString:@"{\"NewsItem\":\"1337679103\",\"PtchItem\":\"1337084310\",\"PlayItem\":\"1336655760\",\"MesgItem\":\"1337615448\",\"BannItem\":\"1337251259\"}"];
//
    NSLog (@"stored %@ string %@",object, items);
    NSDictionary *resultsArray = [items objectFromJSONString];
    NSLog (@"Server's answer: %@",resultsArray);
 
       
    
    for (NSString* object in [resultsArray allKeys]){
//        
//        NSLog(@"arrived: %@",[resultsArray objectForKey:time]);
//        NSLog(@"was: %@",[self.timeStamps objectForKey:time]);

        if([[resultsArray objectForKey:object] intValue]>[[self.timeStamps objectForKey:object]intValue]){
            //data on serevr ios newer
            NSLog(@"Ging to remove object from data store: %@",object);
            [self removeKeys:object];
            
            if ([object isEqualToString:kMessageItem]) [self getData:kGetMessageURL andType:kMessageItem];
            if ([object isEqualToString:kBannerItem]) [self getData:kGetBannerURL andType:kBannerItem];
            
             }
        else {
            //data is not updated
            NSLog(@"Object %@ is not updated",object);
        }
    }

    self.timeStamps=[NSDictionary dictionaryWithDictionary:resultsArray];
//    [self.ss.startButton setHidden:NO];
    [self.ss dismissModalViewControllerAnimated:NO];
    
}


- (void) parseGameItem:(NSString*) object {
    
    //Parses 'bord of matches'. It could fixtures or results. Football or Hurling. 4 different options.
    //Parser generates array of competitions (Competition)
    //each competition has array of matches
    //stores in self.fixturesAndResults dictionary with key according board type
    
    NSLog(@"Matches parser started!");
    
    NSString* items;
    if ([self.serversRespondsStore objectForKey:object]) {
    
        items=[self.serversRespondsStore objectForKey:object];      
    }
    else {
        NSLog(@"No data found!"); 
        return;
    }
    
    NSError* err;
    //    NSLog (@"stored %@ string %@",object, items);
    
    
    NSDictionary *resultsArray = [items objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode error:&err];
    NSLog(@"Error: %@",err);
 
    if (!err) {
        NSLog(@"JSON is OK");
    }
    else {
        NSLog(@"JSON PROBLEMS");
        return;
    }
        
    
    NSMutableArray* tempArray=[[NSMutableArray alloc] initWithObjects:nil];

   
    
//    NSLog (@"stored %@ string %@",object, items);
//    NSLog (@"GAME Server's answer1: %@",resultsArray);
    
    if ([resultsArray count]<1){
        
        NSArray* msg=[[NSArray alloc] initWithObjects:object,@"nodata", nil];
        NSLog(@"empty array!");
        
       
        Competition *allCompetitons=[[Competition alloc] init]; 
       allCompetitons.compname=@"No matches found";
        [tempArray addObject:allCompetitons];


        [self.dataArraysStore setObject:tempArray forKey:object];
        [[NSNotificationCenter defaultCenter]
         postNotificationName:kGameItem
         object:msg];
        return;
    }
    
    Competition *allCompetitons=[[Competition alloc] init]; 
    allCompetitons.compname=kAllCompetitions;
    [tempArray addObject:allCompetitons];

    NSArray *answer=[resultsArray objectForKey:@"competitions"];
    
//    NSLog (@"GAME Server's answer2: %@",answer);
    
    

    //PARSE GAMES
//    NSLog(@"answer: %@",answer);
    for (id item in answer) {
        NSMutableArray* tempMatchArray=[[NSMutableArray alloc] initWithObjects:nil];
        
        //Competition object
        Competition *itemData=[[Competition alloc] init]; 
        
        NSDictionary *itemDict=[item objectForKey:@"competition"];
        
        NSLog(@"Competition: %@",item);
        NSString *name=[self decodeFromURLString:[itemDict objectForKey:@"compname"]];
        NSString *itemid=[itemDict objectForKey:@"compid"];
        
        [itemData setCompname:name];
        [itemData setCompid:itemid];
        [itemData setObjectid:[object substringToIndex:8]];
       
        
        NSArray *matchesArray=[itemDict objectForKey:@"matches"];
//        NSLog(@"Matches (%d): %@",[matchesArray count], matchesArray);

        

        for (id match in matchesArray) {
            Game* game=[[Game alloc] init];
//            NSLog(@"Match: %@",match);

            NSDictionary *itemMatch=[match objectForKey:@"match"];
            
            NSString *dateS=[itemMatch objectForKey:@"date"];
            NSString *time=[itemMatch objectForKey:@"time"];

            int sec=[dateS intValue];
            
            NSRange textRange;
            textRange =[object rangeOfString:@"ixture"];
            
            if (textRange.location != NSNotFound) {
                
                if (sec>946684800) {
                    
                    [game setDateString:[NSString stringWithFormat:@"%@, %@",[self timeStampToStringOnlyDate:sec],time]];
                }
                else {
                    [game setDateString:@"Date: t.b.c."];
                }
            }
            else {
                [game setDateString:[self timeStampToStringOnlyDate:sec]];

            }
            
            [game setDateTimeStamp:[NSNumber numberWithInteger:sec]];
            
            NSString *club1score=[self decodeFromURLString:[itemMatch objectForKey:@"club1score"]];
            NSString *club2score=[self decodeFromURLString:[itemMatch objectForKey:@"club2score"]];
            
            NSString *venue=[self decodeFromURLString:[itemMatch objectForKey:@"venue"]];
            NSString *round=[self decodeFromURLString:[itemMatch objectForKey:@"round"]];
            NSString *club1=[self decodeFromURLString:[itemMatch objectForKey:@"club1"]];
            NSString *club2=[self decodeFromURLString:[itemMatch objectForKey:@"club2"]];
            NSString *referee=[self decodeFromURLString:[itemMatch objectForKey:@"referee"]];
            
            [game setTime:time];
            [game setVenue:venue];
            [game setClub1:club1];
            [game setClub2:club2];
            [game setReferee:referee];
            [game setRound:round];
            [game setClub1score:club1score];
            [game setClub2score:club2score];
            [game.competition setCompid:itemid];
            [game.competition setCompname:name];
            
            [tempMatchArray addObject:game];
            
            
        }
//       NSLog (@"Stored %d matches in %@ competition",[tempMatchArray count],name);
  
        //setting Matches property to competiton array
        [itemData setMatches:tempMatchArray]; 
        
        //adding this competition to array
        [tempArray addObject:itemData]; 
    }
    
    NSLog (@"Parsed %d competitions in %@",[tempArray count],object);
    
    [self.dataArraysStore setObject:tempArray forKey:object];

    
    if ([self.dataArraysStore objectForKey:object]) {
        NSLog (@"F&R: Stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
    } 
    else {
        NSLog (@"WARNING: Not stored %d objects to %@",[[self.dataArraysStore objectForKey:object] count],object);
        
    }
    
    [self.refreshData setObject:[NSNumber numberWithBool:YES] forKey:kGameItem];

     NSArray* msg=[[NSArray alloc] initWithObjects:object,@"ok", nil];
    [[NSNotificationCenter defaultCenter]
     postNotificationName:kGameItem
     object:msg];
}


#pragma mark - Navigation
- (void) createNavigation {

    UIViewController* mainMenuScreen=[[MainMenuViewController alloc] init];
    UINavigationController* navigator=[[UINavigationController alloc] initWithRootViewController:mainMenuScreen];
    navigator.navigationBar.barStyle = UIBarStyleBlack;
    navigator.navigationBar.translucent = YES;
    navigator.navigationBar.tintColor = [UIColor colorWithRed:.25 green:.3 blue:.05 alpha:1];

   // navigator.navigationBar.tintColor=[UIColor greenColor];

    StartScreenViewController* startScreen=[[StartScreenViewController alloc] init];
    self.ss=startScreen;

    
    [self.window setRootViewController:navigator];
    
    [self.window makeKeyAndVisible];
  
    [self.window.rootViewController presentModalViewController:self.ss animated:NO];
    
}

#pragma mark - Security
- (NSData *)doSha1:(NSData *)dataIn
{
    NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1( dataIn.bytes,
            dataIn.length,
            macOut.mutableBytes);
    
    return macOut;
}

#pragma mark - Utilities

- (BOOL ) stringIsEmpty:(NSString *) aString {
    
    if ((NSNull *) aString == [NSNull null]) {
        return YES;
    }
    
    if (aString == nil) {
        return YES;
    } else if ([aString length] == 0) {
        return YES;
    } else {
        aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([aString length] == 0) {
            return YES;
        }
    }
    
    return NO;  
}



-(NSString *) decodeFromURLString: (NSString*) input {
 
    
    if (![self stringIsEmpty:input]) {

        NSString *result = [input stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    result = [result stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    
    return result;
    }
    return @"";
}   

-(NSString *) encodeToURLString: (NSString*) input {
     if (![self stringIsEmpty:input]) {
    NSString* escapedUrlString =
    [input stringByAddingPercentEscapesUsingEncoding:
     NSUTF8StringEncoding];
    
    return escapedUrlString;
     }
    return @"";
}


-(void)msg: (NSString*) text {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"WARNING" 
            message:text
           delegate:self 
    cancelButtonTitle:@"Ok" 
    otherButtonTitles:nil];
    [alert show];
}



- (UIImage *)scale:(UIImage *)image toSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

- (NSString*) timeStampToString:(int) timeStamp {
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:timeStamp];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm dd MMM yyyy"];
    
    //Optionally for time zone converstions
    [formatter setTimeZone:[NSTimeZone defaultTimeZone]];
    
    NSString *stringFromDate = [formatter stringFromDate:date];
    
    return stringFromDate;
    
    
}

- (NSString*) timeStampToString3:(int) timeStamp {
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:timeStamp];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd MMM yyyy HH:mm"];
    
    NSDateFormatter *formatterHoursMins = [[NSDateFormatter alloc] init];
    [formatterHoursMins setDateFormat:@"HH:mm"];

    NSDateFormatter *formatterOnlyDate = [[NSDateFormatter alloc] init];
    [formatterOnlyDate setDateFormat:@"dd MMM yyyy"];

    //Optionally for time zone converstions
    [formatter setTimeZone:[NSTimeZone defaultTimeZone]];
    
    NSString *stringFromDate = [formatter stringFromDate:date];

    NSString *hoursMins = [formatterHoursMins stringFromDate:date];

    NSString *onlyDate = [formatterOnlyDate stringFromDate:date];

    if ([hoursMins isEqualToString:@"00:00"]) return onlyDate;
    
    return stringFromDate;
    
    
}


- (NSString*) timeStampToStringOnlyDate:(int) timeStamp {
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:timeStamp];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd MMM yyyy"];
    
    //Optionally for time zone converstions
    [formatter setTimeZone:[NSTimeZone defaultTimeZone]];
    
    NSString *stringFromDate = [formatter stringFromDate:date];
    
    return stringFromDate;
    
    
}

- (UIImageView*) roundCorners:(UIImageView*)image frameSize:(CGSize)size radius:(float)radius frameBorderThickness:(float) thickness{
    
    image.layer.cornerRadius=radius;
    image.layer.masksToBounds = YES;
    image.layer.borderColor = [UIColor blackColor].CGColor;
    image.layer.borderWidth = thickness;
    CGRect frame = image.frame;

    frame.size.width = size.width;
    frame.size.height = size.height;
    image.frame = frame;
    
    return image;
}
   
   
#pragma mark - Facebook Delegate
- (void)requestLoading:(FBRequest *)request {
    NSLog(@"FB request loading");    
    
}

- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"FB request did receive response");    
    NSLog(@"FB Did receive response: %@",response);
}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
    NSLog(@"FB request did fail");    
    NSLog(@"FB Did fail with error: %@",error);
    
    
}

- (void)request:(FBRequest *)request didLoad:(id)result {
    NSLog(@"FB request did load");    
    NSLog(@"FB Did load result: %@",result);
    
    
}

- (void)request:(FBRequest *)request didLoadRawResponse:(NSData *)data {
    NSLog(@"FB did Load raw response");    
    NSLog(@"didLoadRawResponse: %@",data);
    
    
}


- (void)fbDidExtendToken:(NSString*)accessToken
               expiresAt:(NSDate*)expiresAt {
    NSLog (@"FB Did ExtendToken");
}

- (void)fbDidLogout {
    NSLog(@"FB Did logout");
}
- (void)fbDidNotLogin:(BOOL)cancelled {
    NSLog(@"FB Did not logged");
}

- (void)fbSessionInvalidated {
    NSLog(@"FbSession Invalidated");
}
// Pre iOS 4.2 support
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [self.facebook handleOpenURL:url]; 
}

// For iOS 4.2+ support
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [self.facebook handleOpenURL:url]; 
}

- (void)fbDidLogin {
    NSLog(@"Did logged to FB");
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[self.facebook accessToken] forKey:@"FBAccessTokenKey"];
    [defaults setObject:[self.facebook expirationDate] forKey:@"FBExpirationDateKey"];
    [defaults synchronize];
    
    
}

- (void)startFB {
    _facebook = [[Facebook alloc] initWithAppId:@"283823655032309" andDelegate:self];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"] 
        && [defaults objectForKey:@"FBExpirationDateKey"]) {
        self.facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
        self.facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
    }
    if (![self.facebook isSessionValid]) {
        [self.facebook authorize:nil];
    }
    
    
    if (![self.facebook isSessionValid]) {
        NSArray *permissions = [[NSArray alloc] initWithObjects:
                                //                                @"user_likes",
                                //                                @"user_checkins",
                                //                                @"read_stream",
                                @"publish_stream",
                                //                                @"publish_actions",
                                @"publish_checkins",
                                nil];
        [self.facebook authorize:permissions];
    }
    
    
    //    [self.facebook requestWithGraphPath:@"127747817250603/feed" 
    //                              andParams:[NSMutableDictionary dictionaryWithObject:@"I like it" forKey:@"message"]
    //                          andHttpMethod:@"POST"
    //                            andDelegate:self];
    
    
    
    //    // get information about the currently logged in user
    //    [self.facebook requestWithGraphPath:@"me" andDelegate:self];
    //    
    //    // get the posts made by the "platform" page
    //    [self.facebook requestWithGraphPath:@"me/posts" andDelegate:self];
    //    
    //    // get the logged-in user's friends
    //    [self.facebook requestWithGraphPath:@"me/friends" andDelegate:self];
    
}

#pragma mark - managing DataStore
-(void) loadData {
	NSLog (@"Load data!");
    
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults synchronize];
    
    
    
	if ([defaults objectForKey:@"timeStamps"]) self.timeStamps=[defaults objectForKey:@"timeStamps"];
    if ([defaults objectForKey:@"dataArraysStore"]) {
     NSData *data;
     data=[defaults objectForKey:@"dataArraysStore"];
     NSMutableDictionary *dataDict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        self.dataArraysStore=dataDict;
    }
    
    
    NSLog(@"Data loaded: %@",self.dataArraysStore);
    
	
}


-(void) saveData {
	
	NSLog(@"Save data");
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.dataArraysStore];
    
    [defaults setObject:self.timeStamps forKey:@"timeStamps"];
    [defaults setObject:data forKey:@"dataArraysStore"];

    
	[defaults synchronize];
	
	
    
}





#pragma mark - other UIApllicationDelegate Methods

- (void)applicationWillResignActive:(UIApplication *)application
{
       

    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
   
//    [self saveData];
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    
    
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    
//       [self loadData];


    
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
//    [self saveData];
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

@end
